package cn.zyjblogs.nio;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;


public class NIOFileChannel01 {
    public static void main(String[] args)  {
        String str = "hello 逝水无痕";
        //同创一个输出流-> channel
        try (FileOutputStream fileOutputStream = new FileOutputStream("d:\\file01.txt")){
            //通过fileOutputStream 获取对应的FileChannel 这个FileChannel 正是类型使FileChannelImpl
            FileChannel channel = fileOutputStream.getChannel();

            //创建一个缓冲区ByteBuffer
            ByteBuffer buffer = ByteBuffer.allocate(1024);
            //将src放入byteBuffer中
            buffer.put(str.getBytes());

            //对byteBuffer进行flip 切换为读
            buffer.flip();
            //将ByteBuffer缓冲区数据写入到通道中
            channel.write(buffer);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
